package insight;/*
    @author TTDB
    @create 2025/8/27
*/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayList<E> implements List<E>{
    private Object[] array = new Object[10];
    private int size = 0;
    public void add(E element) {
        if(size == array.length){
            resize();
        }
        array[size] = element;
        size++;

    }

    private void resize() {
        Object[] newArray = new Object[array.length * 2];
        // 复制数组,高级api,参数解释：源数组，源数组的起始位置，目标数组，目标数组的起始位置，复制的长度
        System.arraycopy(array, 0, newArray, 0, array.length);
        array = newArray;
    }

    public void add(int index, E element) {
        if(index > size || index < 0){
            throw new IndexOutOfBoundsException();
        }
        if(size == array.length){
            resize();
        }
        System.arraycopy(array, index, array, index + 1, size - index);
        array[index] = element;
        size++;
    }

    public E remove(int index) {
        if(index > size || index < 0) throw new IndexOutOfBoundsException();
        E e = (E)array[index];
        System.arraycopy(array, index + 1, array, index, size - index - 1);
        size--;
        return e;
    }

    public boolean remove(E element) {
        for(int i = 0; i < size; i++){
            if(array[i].equals(element)){
                System.arraycopy(array, i + 1, array, i, size - i - 1);
                size--;
                return true;
            }
        }
        return false;
    }

    public E get(int index) {
        if(index > size || index < 0) throw new IndexOutOfBoundsException();
        E e = (E)array[index];
        return e;
    }

    public int size() {
        return size;
    }

    public E set(int index, E element) {
        if(index > size || index < 0) throw new IndexOutOfBoundsException();
        E e = (E)array[index];
        array[index] = element;
        return e;
    }

    public Iterator<E> iterator() {
        return new ArrayListIterator();
    }

    class ArrayListIterator implements Iterator<E>{
        private int cursor = 0;
        @Override
        public boolean hasNext() {
            return cursor < size;
        }

        @Override
        public E next() {
            //这个是迭代器的异常信息，超出了index
            if(cursor >= size) throw new NoSuchElementException();
            E e = (E)array[cursor];
            cursor++;
            return e;
        }
    }



}
